package com.hyperboost.interceptor;

import com.hyperboost.properties.JwtProperties;
import com.hyperboost.utils.JwtUtil;
import com.hyperboost.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 判断当前拦截是否需要JWT验证
        if (!(handler instanceof HandlerMethod)) {
            // 如果不是HandlerMethod类型，则不进行JWT验证
            return true;
        }

        try {
            // 从请求头中获取JWT-Token
            String jwtToken = request.getHeader(jwtProperties.getUserTokenName());

            // 解析JWT-Token
            Map<String, Object> claims = JwtUtil.parseToken(jwtProperties.getUserSecretKey(), jwtToken);
            // 存储解析出来的JWT-Token信息到ThreadLocal中
            ThreadLocalUtil.set(claims);

            // 解析成功，则放行
            return true;
        } catch (Exception e) {
            response.sendError(401, "认证失败，请登录！");
            return false;
        }
    }
}
